<!--
 * @Date: 2022-06-13 14:29:31
 * @LastEditTime: 2022-12-22 11:43:29
 * @Description: 登录
-->
<template>
  <view class="page-wrap">
    <view class="loginbox">
      <view class="header-image">
        <image
          src="/static/images/login_header.png"
          mode="widthFix"
        ></image>
      </view>
      <view class="content-wrap">
        <!-- 手机号显示区域 -->
        <view class="phone-display" v-if="loginType === 'quick'">
          <view class="phone-number">{{ maskPhoneNumber }}</view>
          <view class="service-text">XXXXXX服务认证</view>
        </view>

        <!-- 表单登录区域 -->
        <view class="form-container" v-if="loginType === 'code'">
          <view class="input-group">
            <view class="input-item">
              <input
                type="text"
                v-model="form.mobile"
                placeholder="请输入您的手机号"
                class="custom-input"
              />
              <text
                class="clear-icon"
                v-if="form.mobile"
                @click="form.mobile = ''"
              >
                ×
              </text>
            </view>
            <view class="input-item">
              <input
                type="text"
                v-model="form.code"
                placeholder="输入验证码"
                class="custom-input"
              />
              <button
                class="send-code-btn"
                :class="{ disabled: disabledCode }"
                @click="getCode"
              >
                {{ codeSecond ? `${codeSecond}秒后重新获取` : "发送验证码" }}
              </button>
            </view>
          </view>
        </view>

        <!-- 登录按钮区域 -->
        <view class="btn-wrap">
          <button
            class="login-btn"
            :class="{ 'quick-login-btn': loginType === 'quick' }"
            @click="onPhoneLogin"
          >
            {{ loginType === "quick" ? "本机号码一键登录" : "登录" }}
          </button>
        </view>

        <!-- 切换登录方式 -->
        <view class="switch-login" @click="switchLoginType">
          {{ loginType === "quick" ? "验证码登录" : "本机号码一键登录" }}
        </view>
      </view>

      <view class="bottom-section">
        <image
          src="/static/images/login_bg.png"
          mode="widthFix"
          class="bottom-cat-image"
        />
        <view class="agree-box">
          <u-checkbox
            @change="checkboxChange"
            v-model="agreeChecked"
            shape="circle"
          ></u-checkbox>
          <view class="agree-box-text">
            注册或登录即表示已阅读并同意
            <text class="book-style" @click="$common.toRule(1)">
              《用户协议》
            </text>
            和
            <text class="book-style" @click="$common.toRule(7)">
              《隐私协议》
            </text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      customStyle: {
        background: "#1d1d62",
        color: "#fff",
        "border-color": "#1d1d62",
      },
      headImg: "https://ypay.hui-xiang.cn/uploads/other/avatar3.png",
      nickName: "默认微信用户",
      agreeChecked: false,
      anShow: false,
      optionsData: "",
      formData: {
        loginCode: "",
        mobileCode: "",
      },
      form: {
        mobile: "",
        password: "",
        code: "",
      },
      showReg: false,
      sysConfig: "",
      code: "",
      codeSecond: 0,
      codename: "获取验证码",
      disabledCode: false,
      timer: null,
      isLogin: true,
      tokens: "",
      loginType: "code", // 'code': 验证码登录, 'quick': 一键登录
      maskPhoneNumber: "197****3456", // 脱敏的手机号
    };
  },
  computed: {
    ...mapGetters(["appConfig"]),
  },
  onLoad(options) {
    plus.android.importClass("android.telephony.TelephonyManager");

    let context = plus.android.importClass("android.content.Context");
    let TelephonyManager = plus.android
      .runtimeMainActivity()
      .getSystemService(context.TELEPHONY_SERVICE);

    let OperatorName = TelephonyManager.getSimOperatorName();
    let phoneNumber = TelephonyManager.getLine1Number();

    console.log(`运行商名称:${OperatorName}`);
    console.log(`手机号:${phoneNumber}`);

    console.log("options", options);
    this.optionsData = options;
    // this.login()
    this.$store.dispatch("getAppConfig").then((res) => {
      this.sysConfig = res.data;
    });
  },
  onShow() {
    this.tokens = uni.getStorageSync("token");
  },
  methods: {
    funIsLogin() {
      this.isLogin = !this.isLogin;
    },
    getCode() {
      if (this.form.mobile) {
        this.codeSecond = 60;
        this.disabledCode = true;
        this.timer = setInterval(() => {
          if (this.codeSecond >= 1) {
            this.codeSecond--;
          } else {
            this.disabledCode = false;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
        let token = uni.getStorageSync("token");
        let type = 0;
        if (token) {
          type = 2;
        } else {
          type = 1;
        }
        this.req({
          url: "/v1/sms/send",
          method: "POST",
          data: {
            mobile: this.form.mobile,
            type: type,
          },
          Loading: true,
          success: (res) => {
            console.log(res);
            // this.form.code = res.data.code
            this.$u.toast(res.msg);
            // if (res.code == 200) {
            //   uni.setStorageSync(
            //     'token',
            //     `${res.data.token_type}${res.data.access_token}`
            //   )
            //   uni.reLaunch({
            //     url: '/pages/index/index'
            //   })
            // } else {
            //   uni.showToast({
            //     title: res.msg,
            //     mask: true
            //   })
            // }
          },
        });
      } else {
        this.$u.toast("请先输入手机号");
      }
    },
    onPhoneLogin() {
      if (!this.agreeChecked) {
        uni.showToast({
          title: "请先同意协议",
          icon: "error",
          mask: true,
        });
        // this.anShow = true
        return;
      }
      if (this.isLogin) {
        // 登陆接口
        const loginData = {
          type: this.loginType === "quick" ? 2 : 1,
          mobile: this.form.mobile
        };

        if (this.loginType === "code") {
          loginData.code = this.form.code;
        }

        this.req({
          url: "/v1/user/loginUser",
          data: loginData,
          header: {
            Authorization: JSON.parse(
              JSON.stringify(uni.getStorageSync("token"))
            ),
          },
          Loading: true,
          success: (res) => {
            console.log(res);
            if (res.code == 200) {
              uni.setStorageSync(
                "token",
                `${res.data.token_type}${res.data.access_token}`
              );
              uni.reLaunch({
                url: "/pages/index/index",
              });
            } else {
              this.$u.toast(res.msg);
              // uni.showToast({
              //   title: res.msg,
              //   mask: true
              // })
            }
          },
        });
      } else {
        // 注册接口
        this.req({
          url: "/v1/user/registerUser",
          data: this.form,
          Loading: true,
          success: (res) => {
            console.log(res);
            if (res.code == 200) {
              this.isLogin = true;
              uni.showToast({
                title: "注册成功",
                mask: true,
              });
              uni.setStorageSync("token", res.data.access_token);
              uni.reLaunch({
                url: "/pages/index/index",
              });
            } else {
              uni.showToast({
                title: res.msg,
                mask: true,
              });
            }
          },
        });
      }
      return;
      setTimeout(() => {
        this.pageTo();
      }, 800);
      return;
      this.req({
        url: "/v1/user/login",
        data: {
          code: data.code,
        },
        success: (res) => {
          if (res.code == 200) {
            uni.setStorageSync(
              "token",
              `${res.data.token_type}${res.data.access_token}`
            );
            console.log(res);

            setTimeout(() => {
              uni.showToast({
                title: "登录成功",
                mask: true,
              });
            }, 100);

            setTimeout(() => {
              this.pageTo();
            }, 800);
          } else if (res.code == 1001) {
            this.code = data.code;
            console.log("未注册");
            this.anShow = true;
          }
        },
      });
    },
    formSubmit: function (e) {
      console.log(
        "form发生了submit事件，携带数据为：" + JSON.stringify(e.detail.value)
      );
      var formdata = e.detail.value;
      uni.showModal({
        content: "表单数据内容：" + JSON.stringify(formdata),
        showCancel: false,
      });
    },
    formReset: function (e) {
      console.log("清空数据");
    },
    uploadImage(tempFilePaths) {
      console.log(this.siteBaseUrl);
      let _this = this;
      uni.uploadFile({
        url: this.siteBaseUrl + "/v1/upload/image", //接口地址
        filePath: tempFilePaths,
        name: "image",
        success: (res) => {
          let data = JSON.parse(res.data);
          // console.log(data,'image');
          this.headImg = data.data;
          uni.hideLoading();
        },
        fail: (res) => {
          console.log(res);
        },
      });
    },
    onChooseAvatar(e) {
      const avatarUrl = e.detail.avatarUrl; // 此处是头像的临时路径
      console.log(e);
      // 需要后端配合，获得线上的地址
      this.uploadImage(avatarUrl);
    },
    bindblur(e) {
      this.nickName = e.detail.value; // 获取微信昵称
    },
    checkboxChange() {
      this.agreeChecked = true;
    },
    /**
     * @description: 统一处理登录后页面跳转传参
     * @param {*}
     * @return {*}
     */
    pageTo() {
      this.$store.dispatch("getUserInfo").then(() => {
        let pages = getCurrentPages();
        console.log(pages);

        console.log("this.optionsData", this.optionsData);
        let data = "";
        if (this.optionsData) {
          let query = this.optionsData;
          if (this.optionsData.page == "package/fuli/fuli-detail") {
            query.is_new = 1;
          }
          data = query;
        }
        /* 小程序码进入 */
        if (this.optionsData.scene) {
          let query = {};
          let arr = this.optionsData.scene.split("_");
          /**
           * 小程序码参数为 1_1_1 格式 参数间通过_分隔
           * 参数1为类型,之后参数为与后台约定的参数
           * 类型:
           * 1 幸运盒子 参数1为分享人id,参数2为盒子id
           * 未完待续...
           */
          if (arr[0] == 1) {
            query.userId = arr[1];
            query.id = arr[2];
          }
          data = query;
        }

        uni.redirectTo({
          url: `${this.optionsData.page}${this.$common.qs(this.optionsData)}`,
          fail: (err) => {
            console.log("跳转失败--", this.optionsData.page);
            uni.switchTab({
              url: `${this.optionsData.page}`,
            });
          },
        });
      });
    },

    /**
     * @description: 清除注册信息
     * @param {*}
     * @return {*}
     */
    clearForm() {
      this.formData = this.$options.data().formData;
      console.log("clearOk");
    },

    /**
     * @description: 用户注册
     * @param {*}
     * @return {*}
     */
    async reg(e) {
      let wxData = await this.$common.wxMpLogin();
      let data = {};

      data.loginCode = wxData.code;
      data.nickName = this.nickName;
      data.avatarUrl = this.headImg;
      data.invite_code = uni.getStorageSync("invite_code", "");
      /* 小程序码进入 */
      this.req({
        url: "/v1/user/register",
        data,
        success: (res) => {
          console.log(res);
          if (res.code == 200) {
            uni.setStorageSync(
              "token",
              `${res.data.token_type}${res.data.access_token}`
            );

            setTimeout(() => {
              uni.showToast({
                title: "登录成功",
                icon: "success",
                mask: true,
              });
            }, 100);

            setTimeout(() => {
              this.pageTo();
            }, 800);
          }
        },
      });
    },

    /**
     * @description: 获取注册信息
     * @param {*}
     * @return {*}
     */
    getInfo(e) {
      /* 获取登录code */
      if (this.formData.loginCode === "") {
        this.$common.wxMpLogin().then((res) => {
          this.formData.loginCode = res.code;
          this.reg("login");
        });
      }

      /* 获取手机号code */
      if (this.formData.mobileCode === "") {
        console.log(e);
        if (e.type == "getphonenumber") {
          this.formData.mobileCode = e.detail.code;
          this.reg("phone");
        }
      }
    },

    /**
     * @description:
     * @param {*}
     * @return {*}
     */
    async login() {
      if (!this.agreeChecked) {
        uni.showToast({
          title: "请先同意协议",
          icon: "error",
          mask: true,
        });
        return;
      }
      let data = await this.$common.wxMpLogin();
      console.log(data);
      this.req({
        url: "/v1/user/login",
        data: {
          code: data.code,
        },
        success: (res) => {
          if (res.code == 200) {
            uni.setStorageSync(
              "token",
              `${res.data.token_type}${res.data.access_token}`
            );
            console.log(res);

            setTimeout(() => {
              uni.showToast({
                title: "登录成功",
                icon: "success",
                mask: true,
              });
            }, 100);

            setTimeout(() => {
              this.pageTo();
            }, 800);
          } else if (res.code == 1001) {
            this.code = data.code;
            console.log("未注册");
            this.anShow = true;
            // uni.showToast({
            //   title: '请点击授权登录',
            //   icon: 'none'
            // })
          }
        },
      });
    },
    switchLoginType() {
      this.loginType = this.loginType === "code" ? "quick" : "code";
      this.form.mobile = '';
      this.form.code = '';
      this.codeSecond = 0;
      this.disabledCode = false;
    },
  },
};
</script>

<style lang="scss">
.page-wrap {
  min-height: 100vh;
  background-image: url("/static/images/backg.png");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}

.loginbox {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  position: relative;
}

.header-image {
  margin-top: 50rpx;
  width: 100%;
  image {
    width: 100%;
  }
}

.content-wrap {
  flex: 1;
  padding: 0 40rpx;
}

.phone-display {
  text-align: center;
  margin-top: 100rpx;

  .phone-number {
    font-size: 48rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }

  .service-text {
    font-size: 28rpx;
    color: #666;
  }
}

.form-container {
  margin-top: 60rpx;
}

.input-group {
  .input-item {
    position: relative;
    margin-bottom: 20rpx;

    .custom-input {
      width: 100%;
      height: 100rpx;
      background: #fff;
      border-radius: 12rpx;
      padding: 0 30rpx;
      font-size: 28rpx;
      box-sizing: border-box;
      border: 6rpx solid #333;
      color: #333;

      &::placeholder {
        color: #999;
      }
    }

    .clear-icon {
      position: absolute;
      right: 30rpx;
      top: 50%;
      transform: translateY(-50%);
      color: #999;
      font-size: 40rpx;
      line-height: 1;
      padding: 10rpx;
    }

    .send-code-btn {
      position: absolute;
      right: 20rpx;
      top: 50%;
      transform: translateY(-50%);
      background: transparent;
      border: none;
      color: #ff5b5b;
      font-size: 28rpx;
      padding: 20rpx;
      line-height: 1;

      &.disabled {
        color: #999;
      }

      &::after {
        border: none;
      }
    }
  }
}

.btn-wrap {
  margin-top: 60rpx;
  padding: 0 30rpx;

  .login-btn {
    width: 100%;
    height: 100rpx;
    background: #ff5b5b;
    border-radius: 12rpx;
    color: #fff;
    font-size: 32rpx;
    border: 6rpx solid #000;

    &.quick-login-btn {
      background: #ff6b6b;
    }

    &::after {
      border: none;
    }
  }
}

.switch-login {
  text-align: center;
  font-weight: 400;
font-size: 32rpx;
color: #9E1E2D;
  margin-top: 56rpx;
}

.bottom-section {
  position: relative;
  width: 100%;

  .bottom-cat-image {
    width: 100%;
    display: block;
    vertical-align: bottom;
  }

  .agree-box {
    position: absolute;
    bottom: 40rpx;
    left: 0;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1;

    .agree-box-text {
      font-size: 24rpx;
      color: rgba(0, 0, 0, 0.85);
      margin-left: 10rpx;
    }

    .book-style {
      color: #333;
      text-decoration: underline;
    }
  }
}

::v-deep .u-checkbox {
  .u-checkbox__icon-wrap {
    background-color: transparent !important;
    border-color: rgba(0, 0, 0, 0.5) !important;

    &--checked {
      background-color: #333 !important;
      border-color: #333 !important;
    }
  }
}

// 修改输入框右侧图标的样式
::v-deep .uni-input-wrapper {
  .uni-clear-icon {
    color: #333;
  }
}
</style>
